package cn.jly.spring.jdbc.dao;

import cn.jly.spring.jdbc.bean.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author lanyangji
 * @description
 * @date 2020/11/11 下午 4:24
 */
@Service
public class TransactionTransferDaoImpl implements TransactionTransferDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int updateMoneyByUsername(Account account) {
        return jdbcTemplate.update("update account set money = money - ? where `username` = ?", account.getMoney(), account.getUsername());
    }

    @Override
    public Account getByUsername(String username) {
        return jdbcTemplate.queryForObject(
                "select * from account where username = ?",
                new Object[]{username},
                new RowMapper<Account>() {
                    @Override
                    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                        final Account account = new Account();
                        account.setId(rs.getLong("id"));
                        account.setUsername(rs.getString("username"));
                        account.setMoney(rs.getBigDecimal("money"));
                        return account;
                    }
                }
        );
    }
}
